/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-11-25 13:51:56
 ******************************************************************************/
package cn.com.xy.sms.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetWebUtil;
import cn.com.xy.sms.sdk.net.util.SigntureUtil;
import cn.com.xy.sms.sdk.service.travel.TravelService;
import cn.com.xy.sms.sdk.util.PopupUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;
/*SDK-674 hewengao 20161114 start*/
import cn.com.xy.sms.sdk.util.DuoquUtils;
/*SDK-674 hewengao 20161114 end*/
/***
 * 解析卡片管理
 * 
 * @author Administrator
 * 
 */
public class ParseCardManager {
    final static String CARD_SERVICE_ID = "yunyingshang_s_0001";// ISV
                                                                // 服务标识，字符串型，运营商
    final static String CARD_TYPE = "1003"; // 服务基本类型标识，
    final static String CARD_TAG = "xiaoyuan";// 说明卡片来源标签

    public static String SMS_DATE_TIME = "sms_date_time";

    // /**
    // * 解析短信创建卡片
    // * @param ctx 上下文
    // * @param phoneNumber 短信接入码即短信发送方号码
    // * @param smsCenterNum 短信中心号码,短信发送方的短信中心.接收短信时可以解析到此中心号码值
    // * @param smsContent 短信内容
    // * @param extend
    // * @return Map key:Result value false或true
    // */
    // public static Map<String,Object> parseMsgForCard(Context ctx,String
    // phoneNumber,
    // String smsCenterNum, String smsContent,Map<String,String> extend)throws
    // Exception{
    // if (ctx == null) {
    // throw new Throwable(" Context is null.");
    // }
    //
    // if (phoneNumber == null) {
    // throw new Throwable(" phoneNumber is null.");
    // }
    // if (smsContent == null) {
    // throw new Throwable(" smsContent is null.");
    // }
    // if(!SigntureUtil.checkChannelFuncPower(Constant.POWER_TO_YUNCARD))
    // PopupUtil.getResultMap(false,false);
    // Map<String,Object>
    // res=ParseManager.parseMsg(ctx,phoneNumber,smsCenterNum,smsContent,extend);
    // Map<String, Object> map=null;
    // if(res!=null){
    // map= DexUtil.handerValueMap(res);
    // if(map==null){
    // map= new HashMap<String, Object>();
    // map.put("Result", false);
    // return map;
    // }
    // LogManager.i("parseMsgForCard", "res="+res.toString());
    // LogManager.i("parseMsgForCard", "map="+map.toString());
    // if(((JSONObject) map.get("content")) !=null)
    // LogManager.i("parseMsgForCard", "content="+((JSONObject)
    // map.get("content")));
    //
    // if( map.containsKey("extends")){
    // String id=QueryCard(map, ((String) map.get("extends")).trim() );
    // if(!StringUtils.isNull(id)){
    // return update(map, id);
    // }
    // }
    // return insert(map,UUIDUtils.newId());
    // }else {
    // map= new HashMap<String, Object>();
    // map.put("Result", false);
    // return map;
    // }
    //
    // }

    /**
     * 解析短信创建卡片
     * 
     * @param ctx
     *            上下文
     * @param phoneNumber
     *            短信接入码即短信发送方号码
     * @param smsCenterNum
     *            短信中心号码,短信发送方的短信中心.接收短信时可以解析到此中心号码值
     * @param smsContent
     *            短信内容
     * @param extend
     * @return Map key:Result value false或true
     */
    public static Map<String, Object> parseMsgForCard(Context ctx, String phoneNumber, String smsCenterNum, String smsContent, Map<String, String> extend) throws Exception {
        if (ctx == null) {
            throw new Exception(" Context is null.");
        }

        if (phoneNumber == null) {
            throw new Exception(" phoneNumber is null.");
        }
        if (smsContent == null) {
            throw new Exception(" smsContent is null.");
        }
        /*SDK-707 hewengao/20161226 start*/
        if(extend == null){
            extend = new HashMap<String, String>();
        }
        if (!extend.containsKey("PARSE_TIME_OUT")) {
            extend.put("PARSE_TIME_OUT", String.valueOf(15000));
        }
        /*SDK-707 hewengao/20161226 end*/
        Map<String, Object> res = ParseManager.parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, 0l, extend);
        Map<String, Object> map = null;
        if (res != null && ParseBubbleManager.getParseStatu(res) != -1) {
            if (extend != null && extend.containsKey(SMS_DATE_TIME)) {
                res.put(SMS_DATE_TIME, extend.get(SMS_DATE_TIME));
            }
            map = DexUtil.handerValueMap(res);
            if (map == null) {
                map = new HashMap<String, Object>();
                map.put("Result", false);
                /*SDK-674 hewengao 20161114 start*/
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG,"parseMsgForCard handerValueMap end false",null);
                /*SDK-674 hewengao 20161114 end*/
                return map;
            }
            map.put("Result", true);
            return map;
        } else {
            map = new HashMap<String, Object>();
            map.put("Result", false);
            return map;
        }

    }

    /**
     * 依据航班号和航班时间，获取航班到达时间
     * 
     * @param flightNum
     *            航班号
     * @param flightDate
     *            航班时间
     * @param extend
     *            扩展参数
     * @param callBack
     *            无数据或异常时返回参数为null，正常情况返回参数： index0(String):短信ID
     *            index1(JSONObject):航班信息Json对象 例: {"FlightCompany":"上海航空有限公司",
     *            "FlightDeptimePlanDate":"2014-12-01 18:30:00",
     *            "FlightArrtimePlanDate":"2014-12-01 21:05:00",
     *            "FlightHTerminal":"T2","FlightDep":"上海",
     *            "FlightArr":"广州","FlightQueryTime":1433300561019,
     *            "FlightDepAirport":"上海虹桥国际", "FlightArrAirport":"广州白云国际"}
     */
    public static void queryFlightData(final String id, String flightNum, String flightDate, Map<String, Object> extend, final SdkCallBack xyCallBack) {

        ParseManager.queryFlightData(id, flightNum, flightDate, extend, xyCallBack);

    }

    /**
     * 快递
     * 
     * @param express_name
     * @param express_no
     */
    public static void expressage(final String expressName, final String expressNo, final SdkCallBack xyCallBack) {

        // 没有快递名称或快递单号直接返回
        if (StringUtils.isNull(expressName) || StringUtils.isNull(expressNo)) {
            XyUtil.doXycallBackResult(xyCallBack);// call back to the activity
            return;
        }

        // this callback come from netWork
        XyCallBack netWorkCallBack = new XyCallBack() {
            @Override
            public void execute(final Object... obj) {
                if (obj == null || obj.length < 2) {
                    XyUtil.doXycallBackResult(xyCallBack);// call back to the
                                                          // activity,访问失败
                } else {

                    XyUtil.doXycallBackResult(xyCallBack, obj);
                }
            }
        };

        JSONObject jsonObjectForPost = new JSONObject();
        try {

            jsonObjectForPost.put("express_name", expressName);
            jsonObjectForPost.put("express_no", expressNo);

            NetWebUtil.sendPostRequest(NetWebUtil.WEB_SERVER_URL2, jsonObjectForPost.toString(), netWorkCallBack);

        } catch (JSONException e) {

//            e.printStackTrace();
            LogManager.e(Constant.TAG, "expressage: ", e);

            return;
        }

    }

    /**
     * 根据车次查询本地数据库车次途经站信息，如数据库无相关车次信息则使用联网查询接口
     * 
     * @param id
     *            短信ID
     * @param trainNum
     *            车次号
     * @param from
     *            出发地
     * @param to
     *            目的地
     * @param extend
     *            扩展参数
     * @param callBack
     *            回调函数 无数据或异常时返回参数为null，正常情况返回参数： index0(String):短信ID
     *            index1(JSONObject):车次信息Json对象
     *            例:{"station_list":"[{\"name\":\"重庆北\",\"spt\":\"07:48\", \
     *            "stt\":\"07:48\"},{\"name\":\"广安\",\"spt\":\"09:13\",\"stt\":\"09:20\"}]"
     *            } 其中name为站点名，spt为到站时间，stt为出站时间 index2(String):车次号
     *            index3(String):出发地 index4(String):目的地
     *            index5(boolean):true=联网接口 false=本地接口
     */
    public static void queryTrainInfo(final String id, final String trainNum, final String from, final String to, final Map<String, Object> extend, final SdkCallBack callBack) {
        TravelService.queryTrainInfo(id, trainNum, from, to, extend, callBack);
    }

    /**
     * 判断车次途经站信息是否符合要求
     * 
     * @param stationList
     *            车次途经站信息集合
     * @param from
     *            出发地
     * @param to
     *            目的地
     * @return true:符合要求 false:不符合要求
     */
    public static boolean checkStationList(String stationList, String from, String to) {
        return TravelService.checkStationList(stationList, from, to, false);
    }

    /**
     * 
     * @param ctx
     *            上下文
     * @param phoneNumber
     *            短信接入码即短信发送方号码
     * @param smsCenterNum
     *            短信中心号码,短信发送方的短信中心.接收短信时可以解析到此中心号码值
     * @param smsContent
     *            短信内容
     * @param extend
     * @return json 或者 null
     * @throws Exception
     */

    public static String parseMsgForCardData(Context ctx, String phoneNumber, String smsCenterNum, String smsContent, Map<String, String> extend) throws Exception {
        if (ctx == null) {
            throw new Exception(" Context is null.");
        }

        if (phoneNumber == null) {
            throw new Exception(" phoneNumber is null.");
        }
        if (smsContent == null) {
            throw new Exception(" smsContent is null.");
        }
        if (!SigntureUtil.checkChannelFuncPower(Constant.POWER_TO_YUNCARD))
            PopupUtil.getResultMap(false, false);
        Map<String, Object> res = ParseManager.parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, 0l, extend);
        Map<String, Object> map = null;
        if (res != null && ParseBubbleManager.getParseStatu(res) != -1) {
            map = DexUtil.handerValueMap(res);
            if (map == null) {
                return null;
            }
            LogManager.d("parseMsgForCard", "res=",res.toString());
            LogManager.d("parseMsgForCard", "map=", map.toString());

            /* YUNCARD-21 huangzhiqiang 20160408 start */
            Object contentObj = map.get("content");
            if (contentObj != null && contentObj instanceof JSONObject) {
            /* YUNCARD-21 huangzhiqiang 20160408 end */
//                LogManager.i("parseMsgForCard", "content=" + ((JSONObject) map.get("content")).toString());
                JSONObject ret = ((JSONObject) map.get("theReturn")).put("content", map.get("content"));

                ret.put("title", map.get("title"));
                ret.put("card_tag", CARD_TAG);
                LogManager.i("parseMsgForCard", ret.toString());

                return ret.toString();
            }
        }
        return null;

    }

    private static Map<String, Object> insert(Map<String, Object> map, String card_id) {
        // TODO Auto-generated method stub
        ContentValues values = null;
        Uri uri = Uri.parse("content://com.yunos.lifecard/cards");
        if (map == null) {
            map = new HashMap<String, Object>();
            map.put("Result", false);
            return map;
        }
        String content = ((JSONObject) map.get("content")).toString();

        if (content != null && !content.equals("")) {
            ContentResolver contentResolver = Constant.getContext().getContentResolver();

            Uri insert = null;

            values = (ContentValues) map.get("contentValue");
            if (values != null) {
                values.put("card_id", card_id);
                insert = contentResolver.insert(uri, values);
//                LogManager.d("parseMsgForCard", "insert=" ,insert);
            }
            if (insert == null) {
                map.put("Result", false);
            } else {
                map.put("Result", true);
            }
        } else {
            map.put("Result", false);
        }
        return map;
    }

    private static String QueryCard(Map<String, Object> map, String arg1) {
        ContentValues values = null;
        Uri uri = Uri.parse("content://com.yunos.lifecard/cards");
        ContentResolver contentResolver = Constant.getContext().getContentResolver();
        Cursor cursor = contentResolver.query(uri, null, " arg1 like ? ", new String[] { "%" + arg1 + "%" }, null);
        if (cursor.moveToNext()) {
//            LogManager.i("cc", "cc card_id=" + cursor.getString(cursor.getColumnIndex("card_id")));
            String id = cursor.getString(cursor.getColumnIndex("card_id"));
            cursor.close();
            return id;
        }
        return null;
    }

    private static Map<String, Object> update(Map<String, Object> map, String card_id) {
        // TODO Auto-generated method stub
        ContentValues values = null;
        Uri uri = Uri.parse("content://com.yunos.lifecard/cards/");
        if (map == null) {
            map = new HashMap<String, Object>();
            map.put("Result", false);
            return map;
        }
        String content = ((JSONObject) map.get("content")).toString();

        if (content != null && !content.equals("")) {
            ContentResolver contentResolver = Constant.getContext().getContentResolver();

            int insert = -1;

            values = (ContentValues) map.get("contentValue");
            if (values != null) {
                LogManager.i("parseMsgForCard", "values=" + values);
                values.remove("card_tag");
                insert = contentResolver.update(uri, values, "card_id = ?", new String[] { card_id });
//                LogManager.i("parseMsgForCard", "insert=" + insert);
            }
            map = new HashMap<String, Object>();
            if (insert <= 0) {
                map.put("Result", false);
            } else {
                map.put("Result", true);
            }
        } else {
            map.put("Result", false);
        }
        return map;
    }
}
